CREATE TRIGGER TR_LOG_USER_INSERT ON LOG_USER 
FOR INSERT AS


DECLARE
 @TYPE VARCHAR(1),
 @USR_ID INT,
 @DB INT

IF @@ROWCOUNT = 1
BEGIN

	SELECT
	 @USR_ID = ISNULL(LLI_USER_ID,-1),
	 @TYPE = LLI_TYPE
	FROM inserted 

	IF @USR_ID <> -1 AND @TYPE = 'F'
	BEGIN
		SELECT @DB = COUNT(*) FROM LOG_USER
		WHERE LLI_USER_ID = @USR_ID
		AND LLI_DATE > ISNULL((SELECT MAX(LLI_DATE) FROM LOG_USER WHERE LLI_USER_ID = @USR_ID AND LLI_TYPE = 'L'),'1999.01.01')

		IF @DB > 5 
		BEGIN
			UPDATE _USER SET
				USR_LOCKED = 'I',
				USR_LOCKED_DATE = GETDATE()
			WHERE USR_ID = @USR_ID
		END
	END

END

